package cn.wen.base.base;

import android.app.Activity;

import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Activity的统一管理类
 */

public class ActivityManager {
    private static volatile ActivityManager mInstance;
    /**
     * 所有打开的Activity
     */
    private CopyOnWriteArrayList<Activity> mActivities;

    private ActivityManager() {
        mActivities = new CopyOnWriteArrayList<>();
    }

    public static ActivityManager getInstance() {
        if (mInstance == null) {
            synchronized (ActivityManager.class) {
                if (mInstance == null) {
                    mInstance = new ActivityManager();
                }
            }
        }
        return mInstance;
    }

    /**
     * 添加统一管理
     */
    public void attach(Activity activity) {
        mActivities.add(activity);
    }

    /**
     * 移除解绑 - 防止内存泄漏
     *
     * @param detachActivity
     */
    public void detach(Activity detachActivity) {
        mActivities.remove(detachActivity);
    }

    /**
     * 根据Activity的类名关闭 Activity
     */
    public void finish(Class<? extends Activity> activityClass) {
        for (int i = 0; i < mActivities.size(); i++) {
            Activity activity = mActivities.get(i);
            if (activity.getClass().getCanonicalName().equals(activityClass.getCanonicalName())) {
                mActivities.remove(activity);
                activity.finish();
                break;
            }
        }
    }

    /**
     * 退出整个应用
     */
    public void exit() {
        int size = mActivities.size();
        for (int i = 0; i < size; i++) {
            Activity activity = mActivities.get(i);
            activity.finish();
        }
        mActivities.clear();
    }

    /**
     * 获取当前的Activity（最前面）
     */
    public Activity getCurrentActivity() {
        return mActivities.get(mActivities.size() - 1);
    }


}
